
package com.example.tx;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class UdpClient {
    private static Address address = new Address();
    private static JsonUtil json = new JsonUtil();
    public void run(int port) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //设置我要发送的内容
            address.setSign("q");
            address.setMess("Hello");
            //开始客户端的服务，和管道的设置
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .option(ChannelOption.SO_RCVBUF, 2048 * 1024)// 设置UDP读缓冲区为2M
                    .option(ChannelOption.SO_SNDBUF, 1024 * 1024)// 设置UDP写缓冲区为1M
                    .handler(new UdpClientHandler());
            //服务端绑定的管道的端口
            Channel ch = b.bind(50112).sync().channel();
            // 向我的服务器发送消息
            ch.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer(json.toJson(address), CharsetUtil.UTF_8),
                    //地址
                    new InetSocketAddress(
                            "120.55.192.149", 10110
                    )));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //优雅的关闭释放内存

        }
    }
    public static void main(String[] args) throws Exception{
        int port = 10110;
        if(args.length>0){
            try{
                port = Integer.parseInt(args[0]);
            }
            catch (NumberFormatException e){
                e.printStackTrace();
            }
        }
        new UdpClient().run(port);
    }
}



